<template>
  <view class="device-upload-page">
    <!-- 顶部导航 -->
    <u-navbar title="发布设备" :auto-back="true" :border-bottom="true" />
    
    <scroll-view scroll-y class="page-content">
      <!-- 上传进度 -->
      <view class="progress-section" v-if="uploading">
        <u-steps 
          :list="uploadSteps"
          :current="currentStep"
          active-color="#4A90E2"
          direction="row"
        />
      </view>

      <!-- 设备图片上传 -->
      <view class="upload-section content-card">
        <text class="section-title">设备图片</text>
        <text class="section-desc">上传清晰的设备图片，最多9张</text>
        
        <view class="image-upload">
          <view class="image-list">
            <view 
              v-for="(image, index) in formData.images" 
              :key="index"
              class="image-item"
            >
              <image 
                :src="image" 
                class="uploaded-image"
                mode="aspectFill"
                @click="previewImage(index)"
              />
              <view class="image-actions">
                <view class="action-btn" @click="moveImage(index, -1)" v-if="index > 0">
                  <u-icon name="arrow-up" size="12" color="#fff" />
                </view>
                <view class="action-btn" @click="moveImage(index, 1)" v-if="index < formData.images.length - 1">
                  <u-icon name="arrow-down" size="12" color="#fff" />
                </view>
                <view class="action-btn delete" @click="removeImage(index)">
                  <u-icon name="close" size="12" color="#fff" />
                </view>
              </view>
            </view>
            
            <view 
              v-if="formData.images.length < 9"
              class="upload-btn"
              @click="chooseImages"
            >
              <u-icon name="camera" size="32" color="#ccc" />
              <text class="upload-text">添加图片</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="form-section content-card">
        <text class="section-title">基本信息</text>
        
        <u-form :model="formData" ref="formRef" :rules="formRules" :error-type="['toast']">
          <!-- 设备标题 -->
          <u-form-item label="设备标题" prop="title" class="form-item">
            <u-input 
              v-model="formData.title"
              placeholder="请输入设备标题"
              :border="false"
              clearable
            />
          </u-form-item>
          
          <!-- 品牌型号 -->
          <view class="form-row">
            <u-form-item label="品牌" prop="brand" class="form-item half">
              <u-input 
                v-model="formData.brand"
                placeholder="请输入品牌"
                :border="false"
                clearable
              />
            </u-form-item>
            <u-form-item label="型号" prop="model" class="form-item half">
              <u-input 
                v-model="formData.model"
                placeholder="请输入型号"
                :border="false"
                clearable
              />
            </u-form-item>
          </view>
          
          <!-- 设备描述 -->
          <u-form-item label="设备描述" prop="description" class="form-item">
            <u-textarea 
              v-model="formData.description"
              placeholder="请详细描述设备的功能、特点、使用说明等"
              :border="false"
              :maxlength="500"
              height="120"
            />
          </u-form-item>
        </u-form>
      </view>

      <!-- 租赁信息 -->
      <view class="rental-section content-card">
        <text class="section-title">租赁信息</text>
        
        <u-form :model="formData" ref="rentalFormRef" :rules="rentalRules" :error-type="['toast']">
          <!-- 价格设置 -->
          <view class="form-row">
            <u-form-item label="日租金" prop="dailyRent" class="form-item half">
              <u-input 
                v-model="formData.dailyRent"
                placeholder="0"
                type="number"
                :border="false"
                clearable
              >
                <template #suffix>
                  <text class="input-suffix">元/天</text>
                </template>
              </u-input>
            </u-form-item>
            <u-form-item label="押金" prop="deposit" class="form-item half">
              <u-input 
                v-model="formData.deposit"
                placeholder="0"
                type="number"
                :border="false"
                clearable
              >
                <template #suffix>
                  <text class="input-suffix">元</text>
                </template>
              </u-input>
            </u-form-item>
          </view>
          
          <!-- 租期设置 -->
          <view class="form-row">
            <u-form-item label="最少租期" prop="minRentDays" class="form-item half">
              <u-input 
                v-model="formData.minRentDays"
                placeholder="1"
                type="number"
                :border="false"
                clearable
              >
                <template #suffix>
                  <text class="input-suffix">天</text>
                </template>
              </u-input>
            </u-form-item>
            <u-form-item label="最多租期" prop="maxRentDays" class="form-item half">
              <u-input 
                v-model="formData.maxRentDays"
                placeholder="365"
                type="number"
                :border="false"
                clearable
              >
                <template #suffix>
                  <text class="input-suffix">天</text>
                </template>
              </u-input>
            </u-form-item>
          </view>
        </u-form>
      </view>

      <!-- 设备规格 -->
      <view class="specs-section content-card">
        <text class="section-title">设备规格</text>
        <text class="section-desc">添加设备的技术参数和规格信息</text>
        
        <view class="specs-form">
          <view 
            v-for="(spec, index) in formData.specifications" 
            :key="index"
            class="spec-item"
          >
            <view class="spec-inputs">
              <u-input 
                v-model="spec.key"
                placeholder="规格名称"
                :border="false"
                class="spec-key"
              />
              <u-input 
                v-model="spec.value"
                placeholder="规格值"
                :border="false"
                class="spec-value"
              />
            </view>
            <view class="spec-actions">
              <u-button 
                type="error" 
                size="mini"
                @click="removeSpec(index)"
              >
                删除
              </u-button>
            </view>
          </view>
          
          <u-button 
            type="info" 
            size="small"
            @click="addSpec"
            class="add-spec-btn"
          >
            + 添加规格
          </u-button>
        </view>
      </view>

      <!-- 位置信息 -->
      <view class="location-section content-card">
        <text class="section-title">位置信息</text>
        
        <view class="location-form">
          <view class="location-input" @click="selectLocation">
            <text class="location-text" v-if="formData.location.address">
              {{ getFullAddress() }}
            </text>
            <text class="location-placeholder" v-else>点击选择设备位置</text>
            <u-icon name="map-pin" size="16" color="#666" />
          </view>
          
          <view v-if="formData.location.lat && formData.location.lng" class="location-map">
            <map 
              :longitude="formData.location.lng"
              :latitude="formData.location.lat"
              :markers="mapMarkers"
              :scale="15"
              class="map-view"
              show-location
            />
          </view>
        </view>
      </view>

      <!-- 发布设置 -->
      <view class="settings-section content-card">
        <text class="section-title">发布设置</text>
        
        <view class="setting-item">
          <text class="setting-label">立即发布</text>
          <u-switch 
            v-model="formData.autoPublish"
            active-color="#4A90E2"
          />
        </view>
        
        <view class="setting-item">
          <text class="setting-label">接受预约</text>
          <u-switch 
            v-model="formData.acceptReservation"
            active-color="#4A90E2"
          />
        </view>
      </view>

      <!-- 发布按钮 -->
      <view class="publish-section">
        <u-button 
          type="primary" 
          @click="publishDevice"
          :loading="publishing"
          class="publish-btn"
        >
          {{ formData.autoPublish ? '立即发布' : '保存草稿' }}
        </u-button>
        
        <!-- 临时联系客服功能 -->
        <view class="contact-tip">
          <text class="tip-text">设备发布遇到问题？</text>
          <text class="contact-link" @click="contactService">联系客服</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import apiService from '@/api/index.js'

export default {
  data() {
    return {
      formData: {
        title: '',
        brand: '',
        model: '',
        description: '',
        images: [],
        dailyRent: '',
        deposit: '',
        minRentDays: '1',
        maxRentDays: '365',
        specifications: [],
        location: {
          province: '',
          city: '',
          district: '',
          address: '',
          lat: null,
          lng: null
        },
        autoPublish: true,
        acceptReservation: true
      },
      
      formRules: {
        title: [
          { required: true, message: '请输入设备标题', trigger: 'blur' },
          { min: 2, max: 50, message: '标题长度为2-50个字符', trigger: 'blur' }
        ],
        brand: [
          { required: true, message: '请输入设备品牌', trigger: 'blur' }
        ],
        model: [
          { required: true, message: '请输入设备型号', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入设备描述', trigger: 'blur' },
          { min: 10, max: 500, message: '描述长度为10-500个字符', trigger: 'blur' }
        ]
      },
      
      rentalRules: {
        dailyRent: [
          { required: true, message: '请输入日租金', trigger: 'blur' },
          { type: 'number', min: 1, message: '日租金必须大于0', trigger: 'blur' }
        ],
        deposit: [
          { required: true, message: '请输入押金', trigger: 'blur' },
          { type: 'number', min: 0, message: '押金不能小于0', trigger: 'blur' }
        ],
        minRentDays: [
          { required: true, message: '请输入最少租期', trigger: 'blur' },
          { type: 'number', min: 1, message: '最少租期必须大于0', trigger: 'blur' }
        ],
        maxRentDays: [
          { required: true, message: '请输入最多租期', trigger: 'blur' },
          { type: 'number', min: 1, message: '最多租期必须大于0', trigger: 'blur' }
        ]
      },
      
      uploading: false,
      publishing: false,
      currentStep: 0,
      
      uploadSteps: [
        { title: '填写信息' },
        { title: '上传图片' },
        { title: '发布完成' }
      ],
      
      mapMarkers: []
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  methods: {
    initPage() {
      // 初始化一个空的规格项
      this.addSpec()
    },
    
    async chooseImages() {
      try {
        const result = await uni.chooseImage({
          count: 9 - this.formData.images.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        })
        
        if (result.tempFilePaths && result.tempFilePaths.length > 0) {
          await this.uploadImages(result.tempFilePaths)
        }
      } catch (error) {
        console.error('选择图片失败:', error)
      }
    },
    
    async uploadImages(imagePaths) {
      try {
        uni.showLoading({ title: '上传中...' })
        
        const uploadPromises = imagePaths.map(path => this.uploadSingleImage(path))
        const uploadedUrls = await Promise.all(uploadPromises)
        
        this.formData.images = [...this.formData.images, ...uploadedUrls]
        
        uni.hideLoading()
        uni.showToast({
          title: '图片上传成功',
          icon: 'success'
        })
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        })
      }
    },
    
    async uploadSingleImage(imagePath) {
      try {
        const result = await apiService.device.uploadDeviceImage(imagePath)
        return result.url
      } catch (error) {
        throw error
      }
    },
    
    previewImage(index) {
      uni.previewImage({
        urls: this.formData.images,
        current: index
      })
    },
    
    removeImage(index) {
      this.formData.images.splice(index, 1)
    },
    
    moveImage(index, direction) {
      const newIndex = index + direction
      if (newIndex >= 0 && newIndex < this.formData.images.length) {
        const temp = this.formData.images[index]
        this.formData.images[index] = this.formData.images[newIndex]
        this.formData.images[newIndex] = temp
      }
    },
    
    addSpec() {
      this.formData.specifications.push({
        key: '',
        value: ''
      })
    },
    
    removeSpec(index) {
      this.formData.specifications.splice(index, 1)
    },
    
    selectLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.formData.location = {
            province: res.province || '',
            city: res.city || '',
            district: res.district || '',
            address: res.address || '',
            lat: res.latitude,
            lng: res.longitude
          }
          
          this.updateMapMarkers()
        },
        fail: (error) => {
          console.error('选择位置失败:', error)
          uni.showToast({
            title: '选择位置失败',
            icon: 'none'
          })
        }
      })
    },
    
    updateMapMarkers() {
      if (this.formData.location.lat && this.formData.location.lng) {
        this.mapMarkers = [{
          id: 1,
          longitude: this.formData.location.lng,
          latitude: this.formData.location.lat,
          title: this.formData.title || '设备位置',
          iconPath: '/static/map-marker.png',
          width: 30,
          height: 30
        }]
      }
    },
    
    getFullAddress() {
      const location = this.formData.location
      return `${location.province || ''}${location.city || ''}${location.district || ''}${location.address || ''}`
    },
    
    async publishDevice() {
      try {
        // 表单验证
        const [basicValid, rentalValid] = await Promise.all([
          this.$refs.formRef.validate(),
          this.$refs.rentalFormRef.validate()
        ])
        
        if (!basicValid || !rentalValid) return
        
        // 验证图片
        if (this.formData.images.length === 0) {
          uni.showToast({
            title: '请至少上传一张设备图片',
            icon: 'none'
          })
          return
        }
        
        // 验证位置
        if (!this.formData.location.lat || !this.formData.location.lng) {
          uni.showToast({
            title: '请选择设备位置',
            icon: 'none'
          })
          return
        }
        
        this.publishing = true
        
        // 准备提交数据
        const submitData = {
          ...this.formData,
          dailyRent: Number(this.formData.dailyRent),
          deposit: Number(this.formData.deposit),
          minRentDays: Number(this.formData.minRentDays),
          maxRentDays: Number(this.formData.maxRentDays),
          status: this.formData.autoPublish ? 'AVAILABLE' : 'DRAFT',
          specifications: this.formData.specifications.reduce((acc, spec) => {
            if (spec.key && spec.value) {
              acc[spec.key] = spec.value
            }
            return acc
          }, {})
        }
        
        const result = await apiService.device.createDevice(submitData)
        
        uni.showToast({
          title: this.formData.autoPublish ? '发布成功' : '保存成功',
          icon: 'success'
        })
        
        // 返回设备管理页面
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        uni.showToast({
          title: error.message || '发布失败',
          icon: 'none'
        })
      } finally {
        this.publishing = false
      }
    },
    
    // 联系客服
    contactService() {
      uni.makePhoneCall({
        phoneNumber: '0512-6617 4176'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.device-upload-page {
  background: $bg-color;
  min-height: 100vh;
}

.page-content {
  padding: 24rpx;
}

.progress-section {
  margin-bottom: 24rpx;
}

.content-card {
  background: $bg-white;
  border-radius: $border-radius-lg;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: $box-shadow-light;
}

.section-title {
  font-size: $font-size-lg;
  font-weight: $font-weight-bold;
  color: $text-primary;
  margin-bottom: 8rpx;
  display: block;
}

.section-desc {
  font-size: $font-size-sm;
  color: $text-secondary;
  margin-bottom: 24rpx;
  display: block;
}

.image-upload {
  margin-top: 24rpx;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: $border-radius-base;
}

.image-actions {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.action-btn {
  width: 32rpx;
  height: 32rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &.delete {
    background: rgba(255, 71, 87, 0.8);
  }
}

.upload-btn {
  aspect-ratio: 1;
  border: 2rpx dashed $border-color;
  border-radius: $border-radius-base;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.upload-text {
  font-size: $font-size-xs;
  color: $text-tertiary;
}

.form-item {
  margin-bottom: 32rpx;
}

.form-row {
  display: flex;
  gap: 24rpx;
}

.half {
  flex: 1;
}

.input-suffix {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.specs-form {
  margin-top: 24rpx;
}

.spec-item {
  display: flex;
  gap: 16rpx;
  margin-bottom: 16rpx;
  align-items: center;
}

.spec-inputs {
  flex: 1;
  display: flex;
  gap: 16rpx;
}

.spec-key, .spec-value {
  flex: 1;
}

.spec-actions {
  flex-shrink: 0;
}

.add-spec-btn {
  width: 100%;
  margin-top: 16rpx;
}

.location-form {
  margin-top: 24rpx;
}

.location-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx;
  background: $bg-color;
  border-radius: $border-radius-base;
  margin-bottom: 24rpx;
}

.location-text {
  flex: 1;
  font-size: $font-size-base;
  color: $text-primary;
}

.location-placeholder {
  flex: 1;
  font-size: $font-size-base;
  color: $text-tertiary;
}

.location-map {
  height: 300rpx;
  border-radius: $border-radius-base;
  overflow: hidden;
}

.map-view {
  width: 100%;
  height: 100%;
}

.settings-section {
  margin-top: 24rpx;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 2rpx solid $border-color;
  
  &:last-child {
    border-bottom: none;
  }
}

.setting-label {
  font-size: $font-size-base;
  color: $text-primary;
}

.publish-section {
  padding: 40rpx 0;
}

.publish-btn {
  width: 100%;
  height: 88rpx;
  font-size: $font-size-base;
  font-weight: $font-weight-medium;
}

.contact-tip {
  text-align: center;
  margin-top: 24rpx;
  
  .tip-text {
    font-size: $font-size-sm;
    color: $text-secondary;
    margin-right: 16rpx;
  }
  
  .contact-link {
    font-size: $font-size-sm;
    color: $primary-color;
    text-decoration: underline;
  }
}
</style> 